package com.atguigu.srb.gateway.filter;

import com.atguigu.srb.common.util.JwtUtils;
import io.jsonwebtoken.Jwts;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 全局过滤器
 * 网关统一鉴权
 * @author lsyandwh
 * @create 2022-12-13 20:32
 */
@Component
public class MyAuthFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();

        //获取请求头中的token
        List<String> tokens = request.getHeaders().get("token");
        if(! CollectionUtils.isEmpty(tokens)){
            String token = tokens.get(0);
            if(! StringUtils.isEmpty(token)){
                if (JwtUtils.checkToken(token)) {
                    //解析token
                    Long userId = JwtUtils.getUserId(token);
                    //将userId传递到后端
                    request.mutate().header("userId",userId + "");
                    exchange.mutate().request(request);
                }
            }
        }
        System.out.println("网关统一鉴权");
        //放行
        return chain.filter(exchange);
    }
}
